package com.sinszm.web.exception;


import com.sinszm.common.Response;
import com.sinszm.common.exception.SystemApiError;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 捕获非Spring的异常拦截器
 *
 * @author chenjianbo
 */
public class GlobalErrorPageInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        int status = response.getStatus();
        boolean isClientError = status >= 400 && status < 500;
        if (isClientError) {
            writeJavaScript(response, Response.fail(
                    SystemApiError.SYSTEM_ERROR_01,
                    new RuntimeException("客户端请求信息异常")
            ));
            return false;
        }
        boolean isServiceError = status >= 500 && status < 600;
        if (isServiceError) {
            writeJavaScript(response, Response.fail(
                    SystemApiError.SYSTEM_ERROR_01,
                    new RuntimeException("服务器响应信息异常")
            ));
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 将json输出到前端(参数非json格式)
     * @param response  输出上下文
     * @param obj       对象数据
     */
    private void writeJavaScript(HttpServletResponse response, Response<?> obj){
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control","no-store, max-age=0, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials","true");
        try(PrintWriter out = response.getWriter()) {
            out.write(obj.toString());
            out.flush();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }

}